//
//  YQLoginVC.m
//  KingRetail
//
//  Created by yuqin on 2019/6/22.
//  Copyright © 2019 yuqin. All rights reserved.
//

#import "YQLoginVC.h"
#import "YQLoginView.h"
#import "GSRegisterViewController.h"
#import "GSForgetPwdVC.h"
#import "YQNewLoginView.h"
#import "YQSMSCodeVC.h"
#import "YQRegisterVC.h"
#import "YQForgetPwdVC.h"

@interface YQLoginVC ()

@property (nonatomic, strong) YQNewLoginView *loginView;
@property (nonatomic, strong) UIButton *switchBtn;
@property (nonatomic, strong) UIImageView *bgImg;

@end

@implementation YQLoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self.headView setHidden:YES];
    self.view.backgroundColor = WhiteColor;
    self.headView.image = YQ_IMAGE(@"");
    self.headView.backgroundColor = WhiteColor;
    [self.iconAndTitleLeftBtn setImage:YQ_IMAGE(@"back_arrow") forState:UIControlStateNormal];
    //加载loginView
//    [self setupLoginView];
    [self.view addSubview:self.loginView];
    [self.loginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.mas_equalTo(0);
        make.top.equalTo(self.headView.mas_bottom).offset(0);
        make.bottom.mas_equalTo(0);
    }];
    
    [self.loginView addSubview:self.switchBtn];
    [self.switchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.loginView.mas_centerX);
        make.top.mas_equalTo(FIT(50));
        make.size.mas_equalTo(CGSizeMake(FIT(100), FIT(50)));
    }];
    
}

- (void)backAction {
    TheAppDel.rootTabBarController = [[TabBarController alloc] init];
    TheAppDel.window.rootViewController = TheAppDel.rootTabBarController;
}
    
//    [self.view addSubview:self.bgImg];
//    [self.bgImg mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.mas_equalTo(0);
//    }];
    
    //接收通知
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideBgImgView:) name:@"hidesssss" object:nil];
//
//
//- (void)hideBgImgView:(NSNotification *)noti {
//    [UIView animateWithDuration:0.25 animations:^{
//        [self.bgImg removeFromSuperview];
//    }];
//}
//
//- (UIImageView *)bgImg {
//    if (!_bgImg) {
//        _bgImg = [YQViewFactory imageViewWithImage:YQ_IMAGE(@"")];
//        if (HBISIphoneX) {
//            //X以上
//            _bgImg.image = YQ_IMAGE(@"XS_up");
//        }else {
//            _bgImg.image = YQ_IMAGE(@"noX");
//        }
//    }
//    return _bgImg;
//}

- (UIButton *)switchBtn {
    if (!_switchBtn) {
        _switchBtn = [YQViewFactory buttonWithTitle:@"切换环境" titleColor:MainRedTextColor fontSize:FIT(15) userBold:NO target:self sel:@selector(LoginSwitchAction)];
        [_switchBtn setBackgroundColor:WhiteColor];
        _switchBtn.layer.cornerRadius = 3;
        _switchBtn.layer.borderColor = MainRedTextColor.CGColor;
        _switchBtn.layer.borderWidth = 0.5;
        [_switchBtn setHidden:YES];
    }
    return _switchBtn;
}

- (void)LoginSwitchAction {
    [JXTAlertView showAlertViewWithTitle:nil message:nil cancelButtonTitle:nil buttonIndexBlock:^(NSInteger buttonIndex) {
        
        if (buttonIndex == 0) {
            DLog(@"按钮1");
            TheAppDel.requestUrl = ProductBaseHttpUrl;
        }
        else if (buttonIndex == 1) {
            
            DLog(@"按钮2");
            TheAppDel.requestUrl = DevBaseHttpUrl;
        }
        else if (buttonIndex == 2) {
            TheAppDel.requestUrl = UatBaseHttpUrl;
            DLog(@"按钮3");
        }
        
    } otherButtonTitles:@"生产环境",@"测试环境",@"本地环境", nil];
}

- (YQNewLoginView *)loginView {
    if (!_loginView) {
        _loginView = [[YQNewLoginView alloc] init];
        _loginView.backgroundColor = WhiteColor;
        //跳转到获取验证码页面
        //密码登录
        WeakSelf(self);
        _loginView.PwdLoginBlock = ^{
            YQ_PUSH([YQForgetPwdVC new]);
        };
        
        _loginView.LoadCodeBlock = ^{
            //发送成功之后再跳转
            //先判断手机号码是否正确
            //先判断空 再判断格式
            if (isEmptyString(weakSelf.loginView.teleTF.text)) {
                [LCProgressHUD showFailure:@"请输入手机号码"];
                return;
            }
            
            if (![LimitTextFieldNum validateCellPhoneNumber:weakSelf.loginView.teleTF.text]) {
                [LCProgressHUD showFailure:@"请输入正确手机号码"];
                return;
            }
            NSDictionary *parameters = @{@"phoneNum":weakSelf.loginView.teleTF.text,
                                         @"countryCode":@"86"
                                         };
            [LCProgressHUD showLoading:@"加载中..."];
            [SZHTTPSReqManager postRequestWithUrlString:YQ_joiningTogetherUrl(@"users2/loginOrRegisterMsg") appendParameters:nil bodyParameters:parameters successBlock:^(id responseObject) {
                BaseModel *base = [BaseModel modelWithJson:responseObject];
                
                if (base.code == 0) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [LCProgressHUD hide];
                        UserInfo * userInfo = [UserInfo sharedUserInfo];
                        [userInfo mj_setKeyValues:base.data];
                        [UserInfo sharedUserInfo].bIsLogin = YES;
                        
                        YQSMSCodeVC *codeVC = [[YQSMSCodeVC alloc] init];
                        codeVC.teleNum = weakSelf.loginView.teleTF.text;
                        codeVC.isRegister = base.data[@"opType"];
                        codeVC.validateKey = base.data[@"validateKey"];
                        [weakSelf.navigationController pushViewController:codeVC animated:YES];
                    });
                }else {
                    [LCProgressHUD hide];
                }
            } failureBlock:^(NSError *error) {
//                [LCProgressHUD hide];
            }];
        };
    }
    return _loginView;
}

- (void)setupLoginView {
    YQLoginView *loginView = [[YQLoginView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, TableView_Height_IPhoneX+NavigationStatusBarHeight)];
    loginView.teleTF.text = [kDefaults objectForKey:@"loginId"];
    loginView.pwdTF.text = [kDefaults objectForKey:@"password"];
    WeakSelf(self);
    loginView.block = ^(NSDictionary * _Nonnull dict,NSString * _Nonnull pwdStr) {
        //登录成功 跳转
        [SZHTTPSReqManager postRequestWithUrlString:YQ_joiningTogetherUrl(@"users/login") appendParameters:nil bodyParameters:dict successBlock:^(id responseObject) {
            BaseModel * base = [BaseModel modelWithJson:responseObject];
            if (base.code == 0) {
                UserInfo * userInfo = [UserInfo sharedUserInfo];
                [userInfo mj_setKeyValues:base.data];
                [UserInfo sharedUserInfo].bIsLogin = YES;
                //记录token
                //记录账号、密码
                [kDefaults setObject:[responseObject[@"data"] objectForKey:@"token"] forKey:@"token"];
                [kDefaults setObject:[dict objectForKey:@"loginId"] forKey:@"loginId"];
                [kDefaults setObject:pwdStr forKey:@"password"];
                [kDefaults synchronize];
                
                NSLog(@"===== %@",[kDefaults objectForKey:@"token"]);
                
                [LCProgressHUD showSuccess:@"登录成功"];
                //跳转首页
                TheAppDel.window.rootViewController =[TabBarController singletonTabBarController];
            }else {
                [UserInfo sharedUserInfo].bIsLogin = NO;
                [LCProgressHUD showFailure:responseObject[@"msg"]];
            }
        } failureBlock:^(NSError *error) {
            [UserInfo sharedUserInfo].bIsLogin = NO;
        }];
    };
    
    //注册、忘记密码
    
    loginView.registerBlock = ^(NSInteger tag) {
        if (tag == 100) {
            YQ_PUSH([[GSForgetPwdVC alloc] init]);
        }else {
            YQ_PUSH([[GSRegisterViewController alloc] init]);
        }
    };
    
    [self.view addSubview:loginView];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
